<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UploadForm
 *
 * @author zangguoping
 */
class UploadForm {
    private $_root;
    /**
     *
     * @var CUploadedFile 
     */
    private $_file;

    public function __construct(CActiveRecord $model, $filename) {
        $this->_file = CUploadedFile::getInstance($model, $filename); //获取表单名为filename的上传信
        $this->_root = dirname(Yii::app()->basePath);
    }

    public function save($filename = null) {
        if($this->_file){
            $dir = '/assets/upload/' . date('Y/m/d');
            $this->mkdir($dir);
            if (!$filename) {
                $filename = $dir . DIRECTORY_SEPARATOR . md5(time()) . '.' . $this->_file->getExtensionName();
            }
            if ($this->_file->saveAs($this->_root . $filename, true)) {
                return $filename;
            } else {
                print_r($this->_file->getError());
                return null;
            }
        }
    }

    private function mkdir($dir) {
        $dirs = explode('/', $dir);
        $directory = $this->_root;
        //print_r(posix_getpwuid(fileowner($directory)));

        $old = umask(0);
        foreach ($dirs as $d) {
            $directory.= $d . DIRECTORY_SEPARATOR;
            //echo $directory.'<br>';
            if (is_dir($directory) === false) {
                mkdir($directory);
                umask($old);
                if (!is_writable($directory)) {
               
                    throw new Exception(Yii::t('default', $directory . '目录没有写的权限'));
                }
            }
        }
    }

}
